package com.littleken.foodieService.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.littleken.foodieCommon.enums.DeleteStatusEnum;
import com.littleken.foodieCommon.enums.OrderStatusEnum;
import com.littleken.foodieMapper.OrderItemsMapper;
import com.littleken.foodieMapper.OrderStatusMapper;
import com.littleken.foodieMapper.OrdersMapper;
import com.littleken.foodiePojo.bo.SubmitOrderBO;
import com.littleken.foodiePojo.domain.ItemsDO;
import com.littleken.foodiePojo.domain.ItemsSpecDO;
import com.littleken.foodiePojo.domain.OrderItemsDO;
import com.littleken.foodiePojo.domain.OrderStatusDO;
import com.littleken.foodiePojo.domain.OrdersDO;
import com.littleken.foodiePojo.domain.UserAddressDO;
import com.littleken.foodiePojo.enums.IsCommentEnum;
import com.littleken.foodiePojo.vo.MerchantOrdersVO;
import com.littleken.foodiePojo.vo.OrderVO;
import com.littleken.foodieService.AddressService;
import com.littleken.foodieService.ItemService;
import com.littleken.foodieService.OrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.Period;
import java.util.List;

/*
 * Create by littleken on 2020/11/26 9:59
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrdersMapper ordersMapper;

    @Resource
    private OrderItemsMapper orderItemsMapper;

    @Resource
    private OrderStatusMapper orderStatusMapper;

    @Resource
    private AddressService addressService;

    @Resource
    private ItemService itemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderVO createOrder(SubmitOrderBO submitOrderBO) {

        String userId = submitOrderBO.getUserId();
        String addressId = submitOrderBO.getAddressId();
        String itemSpecIds = submitOrderBO.getItemSpecIds();
        Integer payMethod = submitOrderBO.getPayMethod();
        String leftMsg = submitOrderBO.getLeftMsg();

        // 包邮费用设置为0
        Integer postAmount = 0;

        UserAddressDO address = addressService.getAddress(addressId);

        OrdersDO ordersDO = new OrdersDO();
        ordersDO.setUserId(userId);
        ordersDO.setReceiverName(address.getReceiver());
        ordersDO.setReceiverMobile(address.getMobile());
        //地址 省市区详细地址拼接
        ordersDO.setReceiverAddress(address.getProvince() + " "
                + address.getCity() + " "
                + address.getDistrict() + " "
                + address.getDetail());

        ordersDO.setPostAmount(postAmount);
        ordersDO.setPayMethod(payMethod);
        ordersDO.setLeftMsg(leftMsg);
        ordersDO.setIsComment(IsCommentEnum.NO.getCode());
        ordersDO.setIsDelete(DeleteStatusEnum.NO.getCode());
        ordersDO.setCreatedTime(LocalDate.now());
        ordersDO.setUpdatedTime(LocalDate.now());
        ordersMapper.insert(ordersDO);

        // 2. 循环根据itemSpecIds保存订单商品信息表
        String itemSpecIdArr[] = itemSpecIds.split(",");
        Integer totalAmount = 0;    // 商品原价累计
        Integer realPayAmount = 0;  // 优惠后的实际支付价格累计

        for (String itemSpecId : itemSpecIdArr) {
            int buyCounts = 1;
            ItemsSpecDO itemsSpecDO = itemService.queryItemSpecById(itemSpecId);

            totalAmount += itemsSpecDO.getPriceNormal() * buyCounts;
            realPayAmount += itemsSpecDO.getPriceDiscount() * buyCounts;

            // 2.2 根据商品id，获得商品信息以及商品图片
            String itemId = itemsSpecDO.getItemId();
            ItemsDO item = itemService.getItemById(itemId);
            String imgUrl = itemService.queryItemMainImgById(itemId);

            OrderItemsDO subOrderItem = new OrderItemsDO();
            subOrderItem.setOrderId(ordersDO.getId());
            subOrderItem.setItemId(itemId);
            subOrderItem.setItemName(item.getItemName());
            subOrderItem.setItemImg(imgUrl);
            subOrderItem.setBuyCounts(buyCounts);
            subOrderItem.setItemSpecId(itemSpecId);
            subOrderItem.setItemSpecName(itemsSpecDO.getName());
            subOrderItem.setPrice(itemsSpecDO.getPriceDiscount());
            orderItemsMapper.insert(subOrderItem);

            //扣库存
            itemService.decreaseItemSpecStock(itemSpecId, buyCounts);
        }

        ordersDO.setTotalAmount(totalAmount);
        ordersDO.setRealPayAmount(realPayAmount);
        ordersMapper.updateById(ordersDO);

        OrderStatusDO orderStatusDO = new OrderStatusDO();
        orderStatusDO.setOrderStatus(OrderStatusEnum.WAIT_PAY.getCode());
        orderStatusDO.setCreatedTime(LocalDate.now());
        orderStatusMapper.insert(orderStatusDO);

        MerchantOrdersVO merchantOrdersVO = new MerchantOrdersVO();
        merchantOrdersVO.setMerchantOrderId(ordersDO.getId());
        merchantOrdersVO.setMerchantUserId(userId);
        merchantOrdersVO.setAmount(realPayAmount + postAmount);
        merchantOrdersVO.setPayMethod(payMethod);

        OrderVO orderVO = new OrderVO();
        orderVO.setOrderId(ordersDO.getId());
        orderVO.setMerchantOrdersVO(merchantOrdersVO);

        return orderVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String updateOrderStatus(String orderId, Integer orderStatus) {
        OrderStatusDO orderStatusDO = orderStatusMapper.selectById(orderId);
        orderStatusDO.setOrderStatus(orderStatus);
        int i = orderStatusMapper.updateById(orderStatusDO);
        return i == 1 ? orderId : null;
    }

    @Override
    public OrderStatusDO queryOrderStatusInfo(String orderId) {
        return orderStatusMapper.selectById(orderId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> closeOrder() {
        QueryWrapper<OrderStatusDO> wrapper = new QueryWrapper<>();
        wrapper.eq("order_status",OrderStatusEnum.WAIT_PAY.getCode());
        List<OrderStatusDO> orderStatusDOS = orderStatusMapper.selectList(wrapper);
        List<String> deleteList = Lists.newArrayList();
        for (OrderStatusDO orderStatusDO : orderStatusDOS) {
            LocalDate createdTime = orderStatusDO.getCreatedTime();
            LocalDate now = LocalDate.now();
            Period between = Period.between(createdTime, now);
            //过了一天就算过期
            if (between.getDays()>1){
                doCloseOrder(orderStatusDO.getOrderId());
                deleteList.add(orderStatusDO.getOrderId());
            }
        }
        return deleteList;
    }

    @Transactional(rollbackFor = Exception.class)
    boolean doCloseOrder(String orderId) {
        OrderStatusDO orderStatusDO = null;
        orderStatusDO = orderStatusMapper.selectById(orderId);
        if (orderStatusDO != null) {
            orderStatusDO.setOrderStatus(OrderStatusEnum.CLOSE.getCode());
            orderStatusDO.setCloseTime(LocalDate.now());
            int i = orderStatusMapper.updateById(orderStatusDO);
            return i == 1 ? true : false;
        }
        return false;
    }
}
